//
//  MSLogInVC.m
//  MS
//
//  Created by Yuan on 13-3-26.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSLogInVC.h"
#import "MSAppDelegate.h"
#import "MSLogInCell.h"
#import "MSSignUpVC.h"
#import "UIDevice+IdentifierAddition.h"

NSString * const User_AutoLogin = @"com.ms.user_autologin";
NSString * const User_AccountInfo = @"com.ms.user_accountinfo";
NSString * const User_AccountName = @"com.ms.user_accountname";
NSString * const User_AccountPassword = @"com.ms.user_accountpassword";


@interface MSLogInVC ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>
{
    UITableView *loginTableView;
    
    UISwitch *sw;
}
@property(nonatomic,retain) UITableView *loginTableView;

@property(nonatomic,retain) UISwitch *sw;

@end

@implementation MSLogInVC
@synthesize loginTableView;
@synthesize sw;

- (id)init
{
    self = [super init];    
    if (self)
    {

        
        
    }
    return self;
}

-(void)loadView
{
    [super loadView];
    
    CGRect tableViewFrame = CGRectMake(5,10, self.view.frame.size.width-10, 120);
    loginTableView = [[UITableView alloc]initWithFrame:tableViewFrame style:UITableViewStyleGrouped];
    loginTableView.delegate = self;
    loginTableView.dataSource = self;
    loginTableView.backgroundColor = [UIColor clearColor];
    loginTableView.backgroundView = nil;
    [self.view addSubview:loginTableView];
    
    //在ios5里面，添加了tap会导致uibutton事件失效
    UITapGestureRecognizer *g = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapView:)];
    g.delegate = self;
    [self.view addGestureRecognizer:g];
    
    sw = [[UISwitch alloc]initWithFrame:CGRectMake(self.view.frame.size.width-15, loginTableView.frame.origin.y+loginTableView.frame.size.height + 5.0, 0, 0)];
    [sw sizeToFit];
    sw.on = YES;
    [sw addTarget:self action:@selector(changeSwithValue:) forControlEvents:UIControlEventValueChanged];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    sw.on = [[ud objectForKey:User_AutoLogin] boolValue];
    [self.view addSubview:sw];
    UIViewSetFrameX(sw, self.view.frame.size.width - sw.frame.size.width - 15.0);
    
    UILabel *swlbl = [MSTool createLable:CGRectMake(sw.frame.origin.x - 110, sw.frame.origin.y, 100,sw.frame.size.height)];
    [swlbl setTextAlignment:UITextAlignmentRight];
    [swlbl setBackgroundColor:[UIColor clearColor]];
    [swlbl setText:HYLocalizedString(@"记住密码")];
    [self.view addSubview:swlbl];
    
    UIImage *image = [UIImage imageNamed:@"button_bg"];
    
    CGFloat btnWidth = 100.0;
    
    UIButton *signUpBtn = [MSTool createButton:CGRectMake(40,sw.frame.size.height + sw.frame.origin.y + 15,btnWidth, image.size.height) action:@selector(signUp:) delegate:self];
    [signUpBtn setBackgroundImage:[image stretchableImageWithLeftCapWidth:image.size.width/2 topCapHeight:0] forState:UIControlStateNormal];
    [signUpBtn setTitle:HYLocalizedString(@"注册") forState:UIControlStateNormal];
    [self.view addSubview:signUpBtn];

    UIButton *loginBtn = [MSTool createButton:CGRectMake(180,signUpBtn.frame.origin.y, btnWidth, image.size.height) action:@selector(logIn:) delegate:self];
    [loginBtn setBackgroundImage:[image stretchableImageWithLeftCapWidth:image.size.width/2 topCapHeight:0] forState:UIControlStateNormal];
    [loginBtn setTitle:HYLocalizedString(@"登陆") forState:UIControlStateNormal];
    [self.view addSubview:loginBtn];
}

-(void)changeSwithValue:(UISwitch *)sw_
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:[NSNumber numberWithBool:sw_.on] forKey:User_AutoLogin];
    if (!sw_.on) {
        [[MSSetting sharedSetting]resetUserInfo];
    }
    [ud synchronize];
}


-(void)tapView:(UITapGestureRecognizer *)g
{
    [loginTableView.visibleCells makeObjectsPerformSelector:@selector(resignFirstResponder)];
}

//添加事件过滤ios5中uibutton无法相应的问题
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return ! ([touch.view isKindOfClass:[UIControl class]]);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:HYLocalizedString(@"用户登陆") showBackButton:NO];

//    [self setBackItem];
    
	// Do any additional setup after loading the view.
}

-(void)logIn:(UIButton *)btn
{
    MSLogInCell *accountcell = (MSLogInCell *)[loginTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSString *account = accountcell.txtField.text;
    if ([account length]<1)
    {
        [MSTool showAlertTitle:HYLocalizedString(@"提示") message:HYLocalizedString(@"请输入用户名!")];
        return;
    }
    
    MSLogInCell *pwdcell = (MSLogInCell *)[loginTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    NSString *pwd = pwdcell.txtField.text;
    if ([pwd length]<1)
    {
        [MSTool showAlertTitle:HYLocalizedString(@"提示") message:HYLocalizedString(@"请输入密码!")];
        return;
    }

    [self tapView:nil];
    
    NSString *udid = [[UIDevice currentDevice] uniqueDeviceIdentifier];
    NSDictionary *p =  [NSDictionary dictionaryWithObjectsAndKeys:
                        account,@"user_name",
                        pwd,@"password",
                        udid,@"udid",
                        [[MSSetting sharedSetting]getDeviceToken],@"token",
                        nil];
    [WebService  getRequestAction:APIUserLogin
                            param:p
                          success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil)
         {
             HYLog(@"%@",info);
             if (info && [info isKindOfClass:[NSDictionary class]])
             {
                 [[MSAppDelegate sharedAppDelegate] handleUserInfo:info password:pwd];
             }
             [[MSAppDelegate sharedAppDelegate]dismissViewControl];
         }
         [MSTool showError:error];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
     } progress:self.navigationController.view];
    
}



-(void)signUp:(UIButton *)btn
{
    [self loadViewController:NSStringFromClass([MSSignUpVC class])];
}

#pragma mark -UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier=@"Login";
    MSLogInCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell= [[MSLogInCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.accessoryView = nil;
    NSString *imageName = @"";
    NSString *placeHolder = @"";
    switch (indexPath.row) {
        case 0:
            placeHolder = HYLocalizedString(@"请输入用户名");
            imageName = @"smile";
            cell.txtField.secureTextEntry = NO;
            cell.txtField.text = sw.on?[[NSUserDefaults standardUserDefaults] objectForKey:User_AccountName]:@"";
            break;
        case 1:
            placeHolder = HYLocalizedString(@"请输入密码");
            imageName = @"lock";
            cell.txtField.secureTextEntry = YES;
            cell.txtField.text = sw.on?[[NSUserDefaults standardUserDefaults] objectForKey:User_AccountPassword]:@"";
            break;
        default:
            break;
    }
    cell.txtField.placeholder = placeHolder;
    cell.imageName = imageName;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HYLog(@"SS");
}

-(void)back:(UIButton *)btn
{
    [[MSAppDelegate sharedAppDelegate]dismissViewControl];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
